package com.example.tests;

import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserManagementPage;
import com.example.pages.UserPage;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;
import ru.esteru.selenium.factory.WebDriverFactory;

public class ChangePassword {
	private static WebDriver driver;
	private static WebDriverWait wait;
	private static String baseUrl;

	@BeforeClass
	public static void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		wait = new WebDriverWait(driver, 10);
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	public LoginPage loginPage;
	public InternalPage somePage;
	private UserPage userPage;
	private UserManagementPage userManagementPage;

	@Test
	public void newPassword() {

		goToMainPage();
		loginAs("admin", "admin");
		changePassword("admin", "admin");
		assertTrue("User management page doesn't open",
				userManagementPage.isUserManagementOpened());
		logOut();

	}

	public void changePassword(String newPass, String newPass2) {
		somePage.menuMyProfileLink.click();
		userPage.editPasswordField.clear();
		userPage.editPasswordField.sendKeys(newPass);
		userPage.editPassword2Field.clear();
		userPage.editPassword2Field.sendKeys(newPass);
		userPage.saveButton.click();

	}

	private void loginAs(String userName, String password) {

		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(userName);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
		userPage = PageFactory.initElements(driver, UserPage.class);
		userManagementPage = PageFactory.initElements(driver,
				UserManagementPage.class);
	}

	private void logOut() {
		somePage.menuLogoutLink.click();
		wait.until(alertIsPresent()).accept();
	}

}
